package com.food.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.food.entity.pojo.*;
import com.food.entity.dto.FoodReviewDto;
import com.food.entity.vo.FoodReviewVO;
import com.food.mapper.FoodMapper;
import com.food.mapper.UserMapper;
import com.food.mapper.FoodReviewMapper;
import com.food.service.FoodReviewService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FoodReviewServiceImpl extends ServiceImpl<FoodReviewMapper, FoodReview> implements FoodReviewService {

    @Autowired
    private FoodReviewMapper foodReviewMapper;

    @Autowired
    private FoodMapper foodMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void addReview(FoodReviewDto dto) {
        FoodReview review = new FoodReview();
        BeanUtils.copyProperties(review, dto);
        review.setCreatedAt(new Date());
        save(review);
    }

    @Override
    public List<FoodReviewVO> getReviewsByFoodId(Integer foodId) {
        QueryWrapper<FoodReview> wrapper = Wrappers.<FoodReview>query()
                .eq("food_id", foodId);
        return list(wrapper).stream().map(review -> {
            FoodReviewVO vo = new FoodReviewVO();
            BeanUtils.copyProperties(vo, review);

            // 查询用户名
            User user = userMapper.selectById(review.getUserId());
            vo.setUsername(user != null ? user.getUsername() : "未知用户");

            // 查询美食名称
            Food food = foodMapper.selectById(review.getFoodId());
            vo.setFoodName(food != null ? food.getName() : "未知美食");

            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public void deleteReviewById(Integer reviewId) {
        removeById(reviewId);
    }
}
